package com.naiterui.ehp.bp.support.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.naiterui.ehp.bp.support.security.SettingConfig;
import org.apache.commons.lang3.time.DateUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * JWT工具类
 *
 * @author gaoliangliang
 * @date 2019-07-11 12:24
 * @since 1.0.0
 */
public class JwtHelper {

    private static final String SECRET = "token_secret";

    private static final String ISSUER = "system";

    public static String genToken(JwtUser jwtUser) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);
            JWTCreator.Builder builder = JWT
                    .create()
                    .withIssuer(ISSUER)
                    .withExpiresAt(DateUtils.addWeeks(new Date(), 1));
            jwtUser.claims().forEach(builder::withClaim);
            return builder.sign(algorithm);
        } catch (IllegalArgumentException | UnsupportedEncodingException e) {
            return null;
        }
    }

    public static JwtUser verifyToken(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRET);

            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            DecodedJWT jwt = verifier.verify(token);

            return JwtUser
                    .builder()
                    .userId(Long.parseLong(jwt.getClaim("userId").asString()))
                    .userType(Integer.parseInt(jwt.getClaim("userType").asString()))
                    .build();

        } catch (IllegalArgumentException | UnsupportedEncodingException | JWTVerificationException e) {
            return null;
        }
    }

    public static JwtUser parseToken(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return JwtUser
                    .builder()
                    .userId(jwt.getClaim(SettingConfig.USER_ID).asInt().longValue())
                    .userType(jwt.getClaim(SettingConfig.USER_TYPE).asInt())
                    .build();
        } catch (IllegalArgumentException | JWTVerificationException e) {
            return null;
        }
    }

}